# _*_ coding:utf-8 _*_
# @Time  : 2023.04.03
# @Author: zizlee
import json
import datetime
import pandas as pd
import pathlib


def hand_text(t):
    return t.encode('latin1').decode('gbk')


def handle(h_date: datetime.date):
    handle_date_str = h_date.strftime('%Y%m%d')
    file = pathlib.Path('src/ED/cjmx_{}.csv'.format(handle_date_str))
    if not file.exists():
        raise FileNotFoundError('{}的成交明细表数据不存在!'.format(file))

    df = pd.read_csv(file, dtype={0: str, 1: str, 10: str, 11: str,12: str, 13: str, 15: str, 17: str})
    df['cust_name'].fillna('', inplace=True)
    df['wt_kind'].fillna('', inplace=True)
    # cols = df.columns.tolist()
    for c1 in ['ex_date', 'cust_num', 'cust_name', 'seat_name', 'protect', 'wt_kind', 'exl_name', 'variety_name',
               'delivery', 'direction', 'oc_kind', 'ex_num', 'ex_kind', 'contract', 'close_flag']:

        df[c1] = df[c1].apply(lambda x: hand_text(x))
    df.to_csv('src/ExchangeDetail/new/cjmx_{}.csv'.format(handle_date_str), encoding='utf8', index=False)
    print(file)


if __name__ == '__main__':
    with open('ex_dates.json', 'r', encoding='utf8') as dtf:
        date_dict = json.load(dtf)

    date_list = date_dict['2023']
    for d in date_list:
        d_date = datetime.date(int(d[0:4]), int(d[4:6]), int(d[6:8]))
        if d_date <= datetime.date(2023, 3, 22):
            continue
        try:
            handle(h_date=d_date)
        except Exception as e:
            print('----------', d_date)
        else:
            print(d_date)

